﻿using DemoMVC.Filters;
using DemoMVC.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Claims;
using System.Threading.Tasks;

namespace DemoMVC.Controllers
{
    [AllowAnonymous]
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        [Route("")]
        [Route("/")]
        [Route("/Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [SystemActionFilter]
        [SystemExceptionFilter]
        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {

            var claims = new List<Claim>() {
              new Claim(ClaimTypes.Name,user.UserName),
              new Claim("password",user.PassWord)
            };
            var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30),
                IsPersistent = false,
                AllowRefresh = false,
            });
            return RedirectToAction("Privacy");
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 权限页面
        /// </summary>
        /// <returns></returns>
        [SystemActionFilter]
        [SystemAuthenFilter]
        public IActionResult Privacy()
        {
            return View();
        }

        /// <summary>
        /// 错误页面
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
